<!--  -->
<template>
  <div class="orders-container">
    <div class="search-section">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderId"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="loading"
      :data="orders"
      border
      stripe
    >
      <el-table-column prop="orderId" label="订单号" min-width="180" />
      <el-table-column prop="supplierName" label="供应商" min-width="120" />
      <el-table-column prop="totalAmount" label="总金额" width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
        prop="createdAt" 
        label="创建时间" 
        width="180"
        :formatter="(row) => formatDate(row.createdAt)"
      />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleDetail(scope.row)"
          >
            查看详情
          </el-button>
          <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="success"
            @click="handleConfirm(scope.row)"
          >
            确认收货
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        :current-page.sync="pageNum"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-header">
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ currentOrder.orderId }}</span>
          </div>
          <div class="detail-item">
            <span class="label">供应商：</span>
            <span>{{ currentOrder.supplierName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">状态：</span>
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </div>
        </div>

        <el-table :data="currentOrder.items" border>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="price" label="单价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="120">
            <template slot-scope="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="detail-footer">
          <div class="total-amount">
            总计：¥{{ currentOrder.totalAmount }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectAllOrders, getOrderDetails, updateStatusByOrderId } from '@/api/purchaseOrders'
import { formatDate } from '@/utils/date'

export default {
  name: 'PurchaseOrders',
  data() {
    return {
      loading: false,
      orders: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      currentOrder: null,
      searchForm: {
        orderId: ''
      }
    }
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    formatDate,
    async fetchOrders() {
      this.loading = true
      try {
        const res = await selectAllOrders(this.pageNum)
        if (res.code === 200) {
          this.orders = res.data.list || []
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.msg || '获取订单列表失败')
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败')
      } finally {
        this.loading = false
      }
    },
    getStatusType(status) {
      const types = {
        0: 'warning',  // 待收货
        1: 'success',  // 已完成
        2: 'danger'    // 已取消
      }
      return types[status] || 'info'
    },
    getStatusText(status) {
      const texts = {
        0: '待收货',
        1: '已完成',
        2: '已取消'
      }
      return texts[status] || '未知状态'
    },
    async handleDetail(row) {
      try {
        const res = await getOrderDetails(row.orderId)
        if (res.code === 200) {
          this.currentOrder = res.data
          this.dialogVisible = true
        }
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.$message.error('获取订单详情失败')
      }
    },
    async handleConfirm(row) {
      try {
        await this.$confirm('确认收到该订单商品吗？', '提示', {
          type: 'warning'
        })
        const res = await updateStatusByOrderId(row.orderId)
        if (res.code === 200) {
          this.$message.success('确认收货成功')
          this.fetchOrders()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('确认收货失败:', error)
          this.$message.error('确认收货失败')
        }
      }
    },
    handleSearch() {
      this.pageNum = 1
      this.fetchOrders()
    },
    resetSearch() {
      this.searchForm = {
        orderId: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrders()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.fetchOrders()
    }
  }
}
</script>

<style lang="less" scoped>
.orders-container {
  padding: 20px;

  .search-section {
    background: #fff;
    padding: 18px 20px;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  }

  .pagination-section {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .order-detail {
    .detail-header {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #EBEEF5;

      .detail-item {
        margin-bottom: 10px;
        
        .label {
          color: #606266;
          margin-right: 10px;
        }
      }
    }

    .detail-footer {
      margin-top: 20px;
      text-align: right;

      .total-amount {
        font-size: 16px;
        font-weight: bold;
        color: #F56C6C;
      }
    }
  }
}
</style>